﻿using System.Collections.Generic;
using System.Linq;
using Core.DAL;
using Core.Utils;

namespace Core.BOL
{
    public class GMapPlaceRepository
    {
        private ScoutNetDataContext context = null;

        #region Construtor
        public GMapPlaceRepository()
        {
            context = GeneralUtils.GetDataContext();
        }
        #endregion

        #region Methodes
        public void InsertGMapPlaces(tSite_GMapPlace gMapPlace)
        {
            context.tSite_GMapPlaces.InsertOnSubmit(gMapPlace);
        }

        public List<tSite_GMapPlace> GetMarkersBySectionName(string systemName)
        {
            return GetMarkersBySectionName(systemName, -1, -1);
        }

        public void ConnectAlbumToPlace(int AID, int GID)
        {
            var oldPlace = context.tSite_GMapPlaces.Where(p => p.AID == AID).SingleOrDefault();
            if (oldPlace != null)
            {
                oldPlace.AID = null;
            }

            var currentPlace = context.tSite_GMapPlaces.Where(p => p.ID == GID).SingleOrDefault();
            currentPlace.AID = AID;
        }

        public tSite_GMapPlace GetPlaceByID(int PID)
        {
            return context.tSite_GMapPlaces.Where(p => p.ID == PID).SingleOrDefault();
        }

        public tSite_GMapPlace GetPlaceByAlbumID(int AID)
        {
            return context.tSite_GMapPlaces.Where(p => p.AID == AID).SingleOrDefault();
        }

        public void DeletePlace(int ID)
        {
            var place = context.tSite_GMapPlaces.Where(p => p.ID == ID).SingleOrDefault();

            if(place != null){
                context.tSite_GMapPlaces.DeleteOnSubmit(place);
                context.SubmitChanges();
            }
        }

        public List<tSite_GMapPlace> GetMarkersBySectionName(string systemName, int skip, int take)
        {
            var query = (from n in context.tSite_GMapPlaces
                         join s in context.tSite_Sections on n.SID equals s.ID
                         where s.SystemName == systemName
                         orderby n.DateCamp descending
                         select n);

            if (skip != -1 && take != -1)
            {
                return query.Skip(skip).Take(take).ToList();
            }

            return query.ToList();
        }

        public void Save()
        {
            context.SubmitChanges();
        }
        #endregion
    }
}
